const ora = require('ora');
const chalk = require('chalk');
const webpack = require('webpack');
const util = require('./util');
const config = require('./../config.js');

const { PRODUCT_CONFIG } = process.env;
let webpackConfig = {};
// je源码打包
if (PRODUCT_CONFIG == 'je') {
  webpackConfig = require('./webpack.je.js');
  if (!config.jeentry || config.jeentry.length === 0) {
    console.log(chalk.red('请先配置config.json里的jeentry入口目录'));
    process.exit();
  }
// 插件打包
} else {
  webpackConfig = require('./webpack.config.js');
  if (!config.entry || config.entry.length === 0) {
    console.log(chalk.red('请先配置config.json里的entry入口插件目录'));
    process.exit();
  }
}
const spinner = ora('开始构建项目...');
spinner.start();
let initBbuild = false;
webpack(webpackConfig, (err, stats) => {
  spinner.stop();
  if (!initBbuild) {
    process.stdout.write(
      `${stats.toString({
        assets: true,
        colors: true,
        modules: false,
        children: false,
        chunks: false,
        chunkModules: false,
        warnings: false,
      })}\n\n`
    );
    // util.buildViews(webpackConfig.entry);
    initBbuild = true;
    if (!stats.hasErrors()) {
      console.log(chalk.cyan('  构建成功！\n'));
      PRODUCT_CONFIG != 'je' && util.zip();
    }
  } else {
    // 只输出修改的文件
    const { assets } = stats.compilation;
    for (const key in assets) {
      const file = assets[key];
      const module = key.split('/')[0];
      if (file.emitted) {
        console.log(chalk.cyan(`[${module}]：`), chalk.green(key));
      }
    }
    console.log(chalk.gray(new Date(stats.endTime).toString()), '\n');
  }
  PRODUCT_CONFIG != 'je' && util.copyComment();
});
